export class AMapGeoCode {
  constructor(option) {
    /*
     * option: {
     *  city: "全国",
     *  radius: 1000,
     *  lang: "zh_cn",
     *  batch: false, // 是否批量
     *  extensions: "base"
     * }
     * */
    this.option = option;
    this.loadPlugin = new Promise((resolve) => {
      const { option } = this;
      AMap.plugin('AMap.Geocoder', () => {
        //异步加载插件
        this.geocoder = new AMap.Geocoder(option);
        resolve();
      });
    });
  }
  geocode(address) {
    return new Promise((resolve) => {
      this.loadPlugin.then(() => {
        this.geocoder.getLocation(address, (status, result) => {
          if (status === 'complete' && result.geocodes.length) {
            resolve(result.geocodes[0].location);
          } else {
            resolve(null);
            console.error('根据地址查询位置失败');
          }
        });
      });
    });
  }
  regeocode(lnglat) {
    return new Promise((resolve) => {
      this.loadPlugin.then(() => {
        this.geocoder.getAddress(lnglat, (status, result) => {
          if (status === 'complete' && result.regeocode) {
            resolve(result.regeocode.formattedAddress);
          } else {
            resolve('');
            console.error('根据经纬度查询地址失败');
          }
        });
      });
    });
  }
}
